<template>
	<view>
		<div id="myVideo" ref="myVideo"></div>
	</view>
</template>

<script>
	import vapi from '@/api/index.js';
	import config, {
		play
	} from '@/config';
	import Player from 'xgplayer';
	import {
		Client
	} from '@stomp/stompjs';
	import state from '@/config.js';
	import tokenConfig from '@/utils/request/index.js';

	export default {
		name: 'kvideoSocket',
		props: ['query'],
		data() {
			return {
				isLogin: config.isLogin(),
				videoContext: null,
				freeTime: 360, // 试看秒数 6分钟
				isFree: true,
				drag: false,
				currentPlay: {
					learningStatus: 0,
					learningToken: '',
					sourceType: '2',
					classesId: undefined,
					courseId: undefined,
					chapterId: undefined,
					nodeId: undefined,
					demandLength: 0,
					viewingLength: 0,
					requestFlag: ''
				},
				onLine: navigator.onLine, //  navigator.onLine 获取设备是否可以上网、连接网络
				params: {},
				stompClient: null,
				publishUrl: '/app/courseLearn',
				errorCount: 0
			};
		},

		watch: {
			'currentPlay.viewingLength': {
				handler(newValue) {
					if (newValue > 0) {
						if (this.isFree && newValue >= this.freeTime) {
							this.videoContext.pause();
							this.freePlayOver();
						}
						if (Number(newValue) % 30 === 0) {
							this.onHeartbeatMsg();
						}
						let progress = 0;
						let demandLength = this.currentPlay.demandLength;
						if (newValue >= demandLength - 2 || this.currentPlay.learningStatus === 2) {
							progress = 100;
						} else {
							progress = Number(((newValue / demandLength) * 100).toFixed(2));
						}
						this.$emit('updateProgress', progress);
					}
				},
				deep: true,
				immediate: true
			}
		},
		deactivated() {
			this.videoContext?.destroy();
			this.closeLearnSocket();
		},
		created() {
			// 监听网络
			// 网络由异常到正常时触发
			window.addEventListener('online', this.updateOnlineStatus);

			// 网络由正常到异常触发
			window.addEventListener('offline', this.updateOfflineStatus);
		},

		methods: {
			updateOnlineStatus() {
				this.onLine = true;
				uni.hideLoading();
				if (this.videoContext != null && this.videoContext.paused) {
					this.videoContext.play();
				}
			},
			updateOfflineStatus() {
				this.onLine = false;
				uni.showLoading({
					title: '资源加载中4',
					mask: true
				});
				if (this.videoContext != null && !this.videoContext.paused) {
					this.currentPlay.learningToken = '';
					console.log(this.videoContext);
					this.videoContext.pause();
				}
			},
			// 播放
			async playerAudio(l, s, p) {
				let temp = JSON.parse(JSON.stringify(p));
				if (escape(temp.url).indexOf('%u') >= 0) {
					temp.url = encodeURI(temp.url);
				}

				let learnLength = 0;
				this.params = temp;
				if (temp.learnLength == null) {
					learnLength = temp.duration;
				} else {
					learnLength = temp.learnLength;
				}
				if (s.learnStatus === 2) {
					learnLength = 0;
				}
				if (temp.courseStatus != null && temp.courseStatus > 0) {
					this.isFree = false;
				}
				if (temp.demandLength == temp.learnLength || s.learnStatus === 2) {
					this.drag = false;
				} else {
					this.drag = true;
				}
				if (!this.isFree && this.isLogin) {
					this.currentPlay = {
						learningStatus: s.learnStatus,
						learningToken: '',
						sourceType: '2',
						classesId: temp.classesId,
						courseId: temp.courseId,
						chapterId: temp.chapterId,
						nodeId: temp.nodeId,
						demandLength: Number(temp.demandLength),
						viewingLength: 0,
						requestFlag: ''
					};
					this.initSocket();
				}
				if (this.videoContext) {
					this.videoContext.config.disableProgress = this.drag;
					this.videoContext.src = temp.url;
					this.videoContext.poster = temp.poster;
					this.videoContext.currentTime = Number(learnLength);
				} else {
					await this.$nextTick();

					this.videoContext = new Player({
						id: 'myVideo',
						url: temp.url,
						poster: temp.poster,
						autoplay: true,
						'x5-video-player-type': 'h5', //微信同层播放
						'x5-video-player-fullscreen': false,
						playsinline: true,
						'webkit-playsinlin': true,
						'picture-in-picture-mode': [],
						'show-background-playback-button': false,
						fluid: true,
						defaultPlaybackRate: 1,
						lang: 'zh-cn',
						closeVideoClick: true,
						closeVideoTouch: true,
						lastPlayTimeHideDelay: 5, //提示文字展示时长（单位：秒）
						keyShortcut: 'off',
						//使移动端支持双击暂停/播放
						enableVideoDbltouch: true,
						height: 370,
						miniplayer: false,
						pip: false,
						disableProgress: this.drag, //禁止进度条拖动交互,
						disableLongPress: true
					});
					this.videoContext.currentTime = Number(learnLength);
					this.videoContext.on('play', (e) => this.play(e));

					this.videoContext.on('pause', (e) => this.pause(e));

					this.videoContext.on('ended', (e) => this.ended(e));

					this.videoContext.on('timeupdate', (e) => {
						this.currentPlay.viewingLength = Math.floor(e.currentTime);
					});
				}
			},
			play(e) {
				this.onStartPlayMsg();
			},
			pause(e) {
				this.onPausePlayMsg();
			},
			ended(e) {
				this.onPausePlayMsg();
				uni.showLoading({
					title: '进度同步中...'
				});
				setTimeout(() => {
					uni.hideLoading();
					this.$api.getCourseNodeProgressRedis({
							courseId: this.currentPlay.courseId,
							chapterId: this.currentPlay.chapterId,
							nodeId: this.currentPlay.nodeId,
							classesId: this.currentPlay.classesId
						},
						(e) => {
							e = e || {};
							if (Number(e.learnLength) >= Number(e.demandLength) || e.learnStatus === 2) {
								this.changeNextNode();
							} else {
								this.videoContext.currentTime = Number(e.learnLength);
							}
						},
						(e) => {},
						(c) => {}
					);
				}, 2000);
			},
			// 试看结束
			freePlayOver() {
				var szhy = config.storage(['user_info', 'szhy']);
				for (let i = 1; i < 100; i++) {
					clearInterval(i);
				}
				var that = this;
				var courseStatus = this.params.courseStatus;
				var msg = '试看结束，如需继续观看，请购买课程，是否加入购物车？';
				if (szhy == '01' || szhy == '11') {
					msg = '试看结束，如需继续观看，请前往课程超市进行购买，是否立即前往？';
				} else {
					if (courseStatus == 0) {
						msg = '试看结束，如需继续观看，请购买课程，课程已在购物车中，是否进入购物车去结算？';
					} else if (courseStatus == 2) {
						msg = '试看结束，如需继续观看，请购买课程，课程有存在支付中订单，是否继续支付？';
					}
				}
				uni.showModal({
					title: '提示',
					content: msg,
					success: (res) => {
						if (res.confirm) {
							if (szhy == '01' || szhy == '11') {
								that.$uni.navigate(`/pages/courseMarket/index`, 'switchTab');
							} else {
								if (courseStatus == 0) {
									that.$uni.navigate(`/pages/shoppingCart/index`, 'switchTab');
								} else if (courseStatus == 2) {
									that.$uni.navigate(`/pagesA/order/index`, 'redirectTo');
								} else {
									that.$emit('handleShoppingCart');
								}
							}
						} else if (res.cancel) {}
					}
				});
			},

			// 请求播放下一节
			changeNextNode: function() {
				this.$emit('changeNextNode', this.params.chapterId, this.params.nodeId);
			},
			initSocket() {
				let subscribeUrl = '/user/queue/courseLearn';
				let token = tokenConfig.token.replace('Bearer ', '');
				if (this.stompClient == null && this.isLogin) {
					this.stompClient = new Client({
						brokerURL: state.learnSocketUrl + '?access_token=' + token,
						reconnectDelay: 5000, //重连时间
						onConnect: () => {
							uni.hideLoading();
							if (this.stompClient.connected) {
								this.stompClient.subscribe(subscribeUrl, this.onMessage);
								if (this.videoContext != null && this.videoContext.paused) {
									this.videoContext.play();
								}
							}
						},
						onWebSocketError: () => {
							uni.showLoading({
								title: '资源加载中3',
								mask: true
							});
							if (this.videoContext != null && !this.videoContext.paused) {
								this.currentPlay.learningToken = '';
								this.videoContext.pause();
							}
						},
						onWebSocketClose: () => {
							if (this.stompClient != null) {
								this.stompClient = null;
							}
						}
					});
					this.stompClient.activate();
				}
			},
			learnPublishMsg(body) {
				if (this.onLine && !this.isFree && this.isLogin) {
					if (this.stompClient != null && this.stompClient.connected) {
						this.stompClient.publish({
							destination: this.publishUrl,
							body: body
						});
					} else {
						this.initSocket();
					}
				}
			},
			onMessage(res) {
				//余额（请求一个带token的接口以此来判断用户是否在其他地方登录）
				this.$api.getbalance(
					JSON.stringify({
					}),
					(e) => {
						// console.log(e);
					}
				);
				let obj = JSON.parse(res.body);
				if (this.currentPlay.learningToken === '') {
					this.currentPlay.learningToken = obj.learningToken;
				} else {
					if (this.currentPlay.learningToken != obj.learningToken || obj.status == 1) {
						uni.showLoading({
							title: '资源加载中1',
							mask: true
						});
						this.errorCount++;
						if (this.errorCount > 5) {
							uni.showLoading({
								title: '资源加载中5',
								mask: true
							});
							this.closeLearnSocket();
							if (!this.videoContext.paused) {
								this.currentPlay.learningToken = '';
								this.videoContext.pause();
							}
							setTimeout(() => {
								this.initSocket();
							}, 2000);
						}
						if (this.videoContext.paused) {
							this.videoContext.play();
						} else {
							this.onStartPlayMsg();
						}
						setTimeout(() => {
							uni.hideLoading();
						}, 2000);
					} else {
						this.errorCount = 0;
					}
				}
			},
			onHeartbeatMsg() {
				if (this.currentPlay.learningToken != '') {
					this.currentPlay.requestFlag = '00';
					this.learnPublishMsg(JSON.stringify(this.currentPlay));
				} else {
					this.onStartPlayMsg();
				}
			},
			//发送开始播放消息
			onStartPlayMsg() {
				this.currentPlay.learningToken = '';
				this.currentPlay.requestFlag = '01';
				this.learnPublishMsg(JSON.stringify(this.currentPlay));
			},
			//发送 结束播放|暂停播放 消息
			onPausePlayMsg() {
				if (this.currentPlay.learningToken != '' && this.currentPlay.viewingLength > 0) {
					this.currentPlay.requestFlag = '02';
					this.learnPublishMsg(JSON.stringify(this.currentPlay));
					this.currentPlay.learningToken = '';
				}
			},
			closeLearnSocket() {
				if (this.stompClient !== null) {
					this.stompClient.deactivate();
					this.stompClient = null;
				}
			}
		}
	};
</script>

<style scoped>
	.uni-video-cover {
		z-index: 901 !important;
	}

	.hideMe {
		display: none !important;
	}
</style>